﻿using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;

namespace MyAsyncThreadWin
{
    public partial class Form1 : Form
    {
        int time = 1;
        public Form1()
        {
            InitializeComponent();
        }
        private string LongTimeTask()
        {
            try 
            {
                DataTable dt = null;
                dt.WriteXml("xxx.xml");
                Thread.Sleep(10000);
                return "执行完成";
            }
            catch (Exception ex)
            {
                Action<string> action = ExAction;
                this.timer1.Enabled = false;
                action(ex.Message+"\r\n"+ex.StackTrace);
                return "Error";
                //throw new Exception("Error");
            }
        }

        private void ExAction(string err)
        {
            MessageBox.Show(err);
        }
        private void Callback(IAsyncResult ar)
        {
            string str=(ar.AsyncState as Func<string>).EndInvoke(ar);
            this.timer1.Enabled = false;
            time = 1;
            this.label1.Text = str;
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                Func<string> func = LongTimeTask;
                timer1.Enabled = true;
                IAsyncResult result = func.BeginInvoke(Callback, func);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = "执行时间:" + time.ToString();
            time++;
        }
    }
}
